package com.smiier.skin;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.task.RequestTask;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.AccountGetTask;
import com.smiier.skin.net.AccountGetTask.AccountGetRequest;
import com.smiier.skin.net.AccountGetTask.AccountGetResponse;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalFormat;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

/**
 * @{# Cost2DoctorActivity.java Create on 2014-6-10 下午1:35:57
 * 
 * @author <a href="mailto:evan0502@qq.com">Evan</a>
 * @version 1.0 创建付费咨询
 */

@SuppressLint("InflateParams")
public class Cost2DoctorActivity extends BasicActivity {

	private final String txt_yue = "余额支付（账户余额%s元）",
			txt_chongzhi = "充值并支付剩余金额（%s元）";

	private TextView text_doctor_name;
	private CheckBox check_xieyi;

	private TextView edit_cost, text_tip_text;

	private Button btn_pay_for_yue, btn_pay_for_chongzhi;

	private double currentYue;

	private JSONObject doctor;

	// 问题id，如果不为空，则是创建问题成功后直接指派给某个医生
	String qid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cost_2_doctor);

		init();
		setNavTitle("付费咨询");
		edit_cost = (TextView) findViewById(R.id.edit_cost);
		btn_pay_for_yue = (Button) findViewById(R.id.btn_pay_for_yue);
		btn_pay_for_chongzhi = (Button) findViewById(R.id.btn_pay_for_chongzhi);
		text_doctor_name = (TextView) findViewById(R.id.text_doctor_name);
		check_xieyi = (CheckBox) findViewById(R.id.check_xieyi);
		text_tip_text = (TextView) findViewById(R.id.text_tip_text);
		AccountGetRequest req = new AccountGetRequest();
		req.token = GlobalSettings.sToken;
		AccountGetTask task = new AccountGetTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountGetTask.AccountGetRequest, AccountGetTask.AccountGetResponse>() {
			@Override
			public void onException(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					Exception e) {

			}

			@Override
			public void onComplete(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					AccountGetResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				GlobalSettings.sYue = response.Res;
				String totalAccount = GlobalFormat
						.formatCNY(GlobalSettings.sYue);
				currentYue = Double.parseDouble(totalAccount);
				btn_pay_for_yue.setText(String.format(txt_yue, currentYue));

				String txt = CommonUtility.getText(edit_cost);
				if (CommonUtility.isNull(txt)) {
					txt = "0";
				}
				float cost = Float.parseFloat(txt.toString().replace("元", ""));
				if (cost > currentYue) {
					btn_pay_for_chongzhi.setVisibility(View.VISIBLE);
					btn_pay_for_chongzhi.setText(String.format(txt_chongzhi,
							cost - currentYue));
				} else {
					btn_pay_for_chongzhi.setVisibility(View.GONE);
				}

			}
		});
		add(task);

		try {
			doctor = new JSONObject(getIntent().getStringExtra(
					Constant.IDENTITY_KEY));
			String doctorName = doctor.getString("Name");
			text_doctor_name.setText(String.format(text_doctor_name.getText()
					.toString(), doctorName));
			text_tip_text.setText(String.format(text_tip_text.getText()
					.toString(), doctorName));
			if (!CommonUtility.isNull(getIntent().getStringExtra(
					Constant.IDENTITY_KEY_1))) {
				JSONArray costList = doctor.getJSONArray("CostList");
				String cost = "0元";
				for (int i = 0; i < costList.length(); i++) {
					JSONObject object = costList.getJSONObject(i);
					if (object.getInt("Key") == 2) {
						cost = object.getString("Value") + "元";
						break;
					}
				}
				edit_cost.setText(cost);
			} else {
				edit_cost.setText(doctor.getString("Cost") + "元");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onClick(View view) {
		super.onClick(view);
		if (check_xieyi.isChecked()) {
			int id = view.getId();
			if (id == R.id.btn_pay_for_yue) {
				// 注释，修改点击余额支付不反应
				// if (!btn_pay_for_chongzhi.isShown()) {
				pay();
				// }
			} else if (id == R.id.btn_pay_for_chongzhi) {
				pay();
			}
		} else {
			CommonUtility.tip(activity, "请确认勾选咨询服务用户使用协议");
		}
	}

	@SuppressWarnings("unchecked")
	void pay() {
		final String cost = edit_cost.getText().toString().replace("元", "");
		if (!CommonUtility.isNull(cost)) {
			boolean isInvite2Zixun = getIntent().getBooleanExtra(
					Constant.IDENTITY_KEY_COST_MUST_OVER_ZERO, false);
			if (isInvite2Zixun) {
				if (Float.parseFloat(cost) <= 0) {
					CommonUtility.tip(activity, "请输入大于0的有效的数字");
					return;
				}
			}
			if (currentYue == 0 && Float.parseFloat(cost) > 0) {
				Intent intent = new Intent(activity, ChongzhiActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, cost);
				startActivity(intent);
			} else {
				// 支付钱先检查是否初始化过支付密码
				RequestTaskIntercept.requestIntercept(activity,
						Constant.URL.REQUEST, new RequestHandler(activity,
								new HandlerCallback() {

									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											try {
												JSONObject object = (JSONObject) o;
												// 是否初始化支付密码
												boolean isInit = object
														.getBoolean(Constant.JSON_PARAM_RES);
												if (isInit) {
													View v = LayoutInflater
															.from(activity)
															.inflate(
																	R.layout.view_pay_page,
																	null);
													TextView ok = (TextView) v
															.findViewById(R.id.button_ok);
													TextView cancel = (TextView) v
															.findViewById(R.id.button_cancel);
													TextView text_after_pay = (TextView) v
															.findViewById(R.id.text_after_pay);
													final EditText edit_pay_password = (EditText) v
															.findViewById(R.id.edit_pay_password);

													double c = Double
															.parseDouble(cost);
													if (c - currentYue > 0) {
														c = currentYue;
													}
													text_after_pay
															.setText("您即将用您的账户余额支付:"
																	+ cost
																	+ "元");
													final OAlert alert = new OAlert(
															getContext());
													alert.setTitle("请输入支付密码");
													alert.setContentView(v);
													alert.show();
													ok.setOnClickListener(new OnClickListener() {

														@Override
														public void onClick(
																View v) {
															String password = edit_pay_password
																	.getText()
																	.toString();
															if (!CommonUtility
																	.isNull(password)) {
																HashMap<String, Object> params = new HashMap<String, Object>();
																params.put(
																		Constant.PARAM_API,
																		"Question.Set");
																params.put(
																		Constant.PARAM_TOKEN,
																		GlobalSettings.sToken);
																params.put(
																		"Cost",
																		cost);
																params.put(
																		"Is_Appoint",
																		1);
																params.put(
																		"Status",
																		0);
																// 若inviteCode不为空，则为通过邀请码提问
																String inviteCode = getIntent()
																		.getStringExtra(
																				Constant.IDENTITY_KEY_1);
																if (!CommonUtility
																		.isNull(inviteCode)) {
																	params.put(
																			"invite_code",
																			inviteCode);
																}
																qid = getIntent()
																		.getStringExtra(
																				Constant.IDENTITY_KEY_QUESTION_ID);
																// 如果qid不为空，则是修改当前问题
																if (!CommonUtility
																		.isNull(qid)) {
																	params.put(
																			"qid",
																			qid);
																	params.put(
																			"Status",
																			2);
																}
																try {
																	params.put(
																			"Doctor_Uid",
																			doctor.getString("Uid"));
																} catch (Exception e1) {
																	e1.printStackTrace();
																}
																params.put(
																		"PayPwd",
																		OUtil.md5(password));
																new RequestTask(
																		activity,
																		Constant.URL.REQUEST,
																		new RequestHandler(
																				activity,
																				new HandlerCallback() {

																					@Override
																					public void callback(
																							Object o) {
																						if (!CommonUtility
																								.isNull(o)) {
																							JSONObject object = (JSONObject) o;
																							if (CommonUtility
																									.response200(object)) {
																								if (!CommonUtility
																										.isNull(qid)) {
																									Intent intent = new Intent(
																											activity,
																											CreateQuestionSuccessAndChatActivity.class);
																									intent.putExtra(
																											Constant.IDENTITY_KEY_DOCTOR_INFO,
																											doctor.toString());
																									intent.putExtra(
																											Constant.IDENTITY_KEY,
																											qid);
																									startActivity(intent);
																									CommonUtility
																											.finishActivityFromName(CreateQuestionSuccessfullyActivity.class
																													.getSimpleName());
																									intent = new Intent(
																											Constant.RECIVER_CHAT_LIST);
																									sendBroadcast(intent);
																									intent = new Intent(
																											Constant.RECIVER_UPDATE_QUESTION);
																									sendBroadcast(intent);
																									intent = new Intent(
																											Constant.RECIVER_QUESTION);
																									intent.putExtra(
																											Constant.IDENTITY_KEY_1,
																											true);
																									sendBroadcast(intent);
																									finish();
																								} else {
																									Intent intent = new Intent(
																											activity,
																											Cost2DoctorSuccessActivity.class);
																									intent.putExtra(
																											Constant.IDENTITY_KEY_1,
																											doctor.toString());
																									try {
																										intent.putExtra(
																												Constant.IDENTITY_KEY,
																												object.getJSONObject(
																														Constant.JSON_PARAM_RES)
																														.toString());
																									} catch (Exception e) {
																										e.printStackTrace();
																									}
																									startActivity(intent);
																								}
																							}
																						}
																					}
																				}))
																		.execute(params);
																alert.dismiss();
															} else {
																Toast.makeText(
																		Cost2DoctorActivity.this,
																		"请输入支付密码",
																		Toast.LENGTH_SHORT)
																		.show();
															}

														}
													});
													cancel.setOnClickListener(new OnClickListener() {

														@Override
														public void onClick(
																View v) {
															alert.dismiss();
														}
													});

												} else {
													// 未初始化支付密码，需要提示初始化支付密码
													if (CommonUtility
															.isNull(GlobalSettings.sUser.Mobile)) {
														OAlert alert = new OAlert(
																getContext());
														alert.setOK("确认");
														alert.setCancel("取消");
														alert.setTitle(R.string.s_init_mobile);
														alert.show();
														alert.setListener(new OAlertListener() {

															@Override
															public boolean onOK(
																	OAlert alert) {
																Intent intent = new Intent(
																		activity,
																		RegisterFirstStepActivity.class);
																intent.putExtra(
																		Constant.IDENTITY_KEY_1,
																		Constant.TYPE_UPDATE_MOBILE);
																startActivity(intent);
																return false;
															}

															@Override
															public boolean onCancel(
																	OAlert alert) {
																return false;
															}
														});
													} else {
														OAlert alert = new OAlert(
																getContext());
														alert.setOK("确认");
														alert.setCancel("取消");
														alert.setTitle(R.string.s_init_paypassword);
														alert.show();
														alert.setListener(new OAlertListener() {

															@Override
															public boolean onOK(
																	OAlert alert) {
																try {
																	CommonUtility
																			.confirmSendCode(
																					activity,
																					GlobalSettings.sUser.Mobile,
																					Constant.TYPE_RESET_PAY_PASSWORD);
																} catch (Exception e) {
																	e.printStackTrace();
																}
																return false;
															}

															@Override
															public boolean onCancel(
																	OAlert alert) {
																return false;
															}
														});
													}
												}
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								}), CommonUtility.params(new String[] {
								Constant.PARAM_API, Constant.PARAM_TOKEN },
								new String[] { "Account.CheckInitPayPwd",
										GlobalSettings.sToken }));
			}

		}
	}
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
	
	
}
